import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:practice_flutter/utils/eventbus.dart';
import 'package:practice_flutter/utils/http.dart';
import 'package:practice_flutter/utils/logger.dart';
import 'package:practice_flutter/utils/toast.dart';

// ignore: must_be_immutable
class ProfilePage extends StatefulWidget {
  // ignore: prefer_const_constructors_in_immutables
  ProfilePage({super.key, required this.userInfo});
  Map userInfo;
  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {'avatar': '', 'nickName': ''};
  final TextEditingController _avatarController = TextEditingController();
  //路由传参通过initState中调用widget.userInfo拿到路由传参中的参数
  @override
  void initState() {
    logger.i(widget.userInfo);
    setState(() {
      userInfo = widget.userInfo;
      _avatarController.text = widget.userInfo['nickName'];
    });
    super.initState();
     SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarIconBrightness: Brightness.light, // 状态栏文字和图标颜色为深色
        // statusBarIconBrightness: Brightness.light, // 状态栏文字和图标颜色为浅色
      ),
    );
  }

  //图片选择 只能安卓模拟器
  Future<void> _pickImageFromGallery() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      try {
        FormData formData = FormData.fromMap({
          "file": await MultipartFile.fromFile(pickedFile.path),
          "type": "avatar",
        });
        var res = await http.post('/upload', formData);
        if (res['code'] != 10000) return ToastUtil.showError('上传图片失败!');
        setState(() {
          userInfo['avatar'] = res['data']['url'];
        });
      } finally {
        // ignore: use_build_context_synchronously
        Navigator.pop(context);
      }
    }
  }

  // 更新昵称
  updateNickName() async {
    if (_avatarController.text.isEmpty) {
      return ToastUtil.showError('昵称不能为空!');
    }
    try {
      await http.put('/userInfo', {"nickName": _avatarController.text});
      setState(() {
        userInfo['nickName'] = _avatarController.text;
        ToastUtil.showSuccess('修改成功!');
      });
    } catch (e) {
      return ToastUtil.showError('网络异常!');
    }
  }

  // 从相机或相册中选择图片
  selectAvatar() {
    showModalBottomSheet(
        context: context,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(0)),
        builder: (context) {
          return SizedBox(
              height: 120,
              child: Column(children: [
                ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  onTap: () {},
                ),
                ListTile(
                  leading: const Icon(Icons.photo),
                  title: const Text('相册'),
                  onTap: () {
                    if (kIsWeb) {
                      ToastUtil.showInfo('Web不可用');
                    } else if (Platform.isAndroid) {
                      _pickImageFromGallery();
                    }
                  },
                )
              ]));
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          onPressed: () {
            eventBus.fire(BackMine());
            Navigator.pop(context);
          },
          icon: const Icon(Icons.arrow_back),
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text('头像', style: TextStyle(fontSize: 16)),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        selectAvatar();
                      },
                      child: ClipRRect(
                          borderRadius: BorderRadius.circular(50.0),
                          child: userInfo['avatar'] == ''
                              ? Image.asset('images/avatar_1.jpg',
                                  width: 30, height: 30)
                              : Image.network(userInfo['avatar'],
                                  width: 30, height: 30)),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  decoration: const InputDecoration(
                      hintText: '请输入昵称', border: InputBorder.none),
                  textAlign: TextAlign.right,
                  controller: _avatarController,
                  //当回车我确认时
                  onEditingComplete: () {
                    updateNickName();
                  },
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          )
        ],
      ),
    );
  }
}
